const Service = require("egg").Service;

class BaseService extends Service {
  toId(data, filters = []) {
    if (typeof data !== "object" || !data || data instanceof Buffer || data instanceof this.app.mongoose.Types.ObjectId)
      return data;

    filters = filters.concat(["__v", "isAdmin"]);

    let result;

    if (Array.isArray(data)) {
      result = [];
    } else {
      data = data.toObject ? data.toObject() : data;
      result = {};
    }

    const keys = Object.keys(data);

    for (let i = 0; i < keys.length; i++) {
      const key = keys[i];
      let value = data[key];

      value = this.toId(value, filters);

      if (key === "_id") {
        result.id = value;
      } else if (!filters.includes(key)) {
        result[key] = value;
      }
    }

    return result;
  }
}

module.exports = BaseService;
